﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using calculation.Models;



namespace calculation.Controllers
{
    public class OrderController : Controller
    {
        private DataManager _dataManager;
        public OrderController(DataManager dataManager)
        {
            _dataManager = dataManager;
        }
        public ActionResult List()
        {
            ViewData["Name"] = "Заказы";
            ViewData["Заказы"] = _dataManager.Orders.GetOrders();

            return View();
        }

        public ActionResult Order(int id)
        {
            ViewData.Model = _dataManager.Orders.GetOrders(id);
            return View();
        }
        public ActionResult Delete(int id)
        {
            _dataManager.Orders.DeleteOrder(id);

            return RedirectToAction("List");
        }
        [Authorize(Roles = "Admin")]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Edit(int id)
        {
            Order t = _dataManager.Orders.GetOrders(id);
            ViewData.Model = t;

            SetEditLists(t);
            return View();
        }
                       
        private void SetEditLists(Order t)
        {
            ViewData["States"] = new SelectList(_dataManager.States.GetStates(),
                   "StateId", "Title", t.StateId);
            ViewData["Materials"] = new SelectList(_dataManager.Materials.GetMaterials(),
                   "MaterialId", "Name", t.MaterialId);
            ViewData["Detals"] = new SelectList(_dataManager.Detals.GetDetals(),
                "DetalId", "NameDetal", t.DetalId);
            
        }
        [Authorize(Roles="Admin")]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, Order t)
        {
            if (t.Name.Length <= 3) 
                ModelState.AddModelError("Name", "Name ....");
            

            if (ModelState.IsValid)
            {
                t.OrderId = id;
                _dataManager.Orders.UpdateOrder(t);
                return RedirectToAction("List");
 
            }
            SetEditLists(t);
            return View();

        }

       
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Add()
        {
            Order t = _dataManager.Orders.GetOrders(5);
            ViewData.Model = t;
            SetEditLists(t);
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Add(string name, Material m, Detal d)
        {
            if (name.Length <= 3)
                ModelState.AddModelError("Name", "Name ....");
          

            if (ModelState.IsValid)
            {
                _dataManager.Orders.CreateOrder(name, m,d);
                return RedirectToAction("List");
            }
            return View();
        }
    }
}
